<template>
  <view class="login-wrap" v-if="moduleShow">
    <image
      class="logo"
      :src="logo"
      alt="logo"
      lazy-load
    />
    <view class="header">AI助手</view>

    <view class="containar">
      <view class="avatarUrl">
        <button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
          <image class="refreshIcon" :src="avatarUrl"></image>
        </button>
      </view>

      <view class="userName">
        <text>昵称：</text>
        <input type="nickname" v-model="nickname" @change="getNickNames" class="weui-input" placeholder="请输入昵称" />
      </view>

      <view class="btn">
        <view class="btn-sub" @click="getUserProfile">登录</view>
      </view>
    </view>
  </view>
</template>

<script>
import { LOGIN } from '@/api/cms';
import { logo } from '@/tool/static-img.js';

const defaultAvatarUrl =
  'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0';

const app = getApp();
export default {
  data() {
    return {
      logo,
      moduleShow: false,
      hasMpUser: 0,
      loadBtn: false,
      avatarUrl: defaultAvatarUrl,
      nickname: '',
      mobile: '',
    };
  },
  async onLoad() {
    uni.hideShareMenu();
    this.moduleShow = true;
  },
  methods: {
    onChooseAvatar(e) {
      const { avatarUrl } = e.detail;
      // 不保存临时文件路径，使用默认头像
      // TODO: 如果需要上传用户头像，应在这里调用上传接口
      console.log('用户选择了头像:', avatarUrl);
      this.avatarUrl = avatarUrl; // 仅用于页面预览
    },
    getNickNames(e) {
      this.nickname = e.detail.value;
    },
    getUserProfile() {
      // 用户信息
      // 阻断处理，微信本身自带阻断其实，再加一层
      if (this.loadBtn) {
        return;
      }
      
      if (!this.nickname || this.nickname.trim() === '') {
        uni.showToast({
          title: '请输入昵称',
          icon: 'none'
        });
        return;
      }
      
      console.log('this.nickname====1111=', this.nickname);
      this.loadBtn = true;
      
      // 本地登录，不调用后端接口
      wx.getUserProfile({
        desc: '用于完善个人资料',
        success: async res => {
          console.log('this.nickname=====', this.nickname);
          
          // 使用默认头像，避免临时文件路径问题
          const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0';
          
          // 保存用户信息到本地
          uni.setStorageSync('avatarUrl', defaultAvatarUrl);
          uni.setStorageSync('nickName', this.nickname.trim());
          uni.setStorageSync('gender', 0);
          uni.setStorageSync('isLogin', true);
          uni.setStorageSync('loginTime', new Date().getTime());
          
          this.loadBtn = false;
          
          uni.showToast({
            title: '登录成功',
            icon: 'success',
            duration: 1500
          });
          
          // 延迟跳转，让用户看到成功提示
          setTimeout(() => {
            this.backReload();
          }, 1500);
        },
        fail: async () => {
          console.log('用户拒绝授权');
          this.loadBtn = false;
          uni.showToast({
            title: '需要授权才能使用',
            icon: 'none'
          });
        }
      });
    },
    backReload() {
      // 返回上一页,无上一页跳转初始记录页
      const pages = getCurrentPages();
      if (pages.length >= 2) {
        // 此类情况适用于临时登录，购买分享时的二次登录场景，及登录失效时处理
        const beforePage = pages[pages.length - 2];

        if (beforePage.route === 'pages/login/index') {
          uni.reLaunch({ url: '/pages/chat/index' });
          return;
        }

        uni.navigateBack({
          delta: 1,
          success: () => {
            if (beforePage.route === 'pages/chat/index') {
              // 触发上一页更新，主要页面加上重更新机制就行
              beforePage.onLoad({
                type: 'fromLogin',
              });
            } else {
              beforePage.onShow({
                type: 'fromLogin',
              });
            }
          },
        });
      } else {
        uni.reLaunch({ url: '/pages/chat/index' });
      }
    },
  },
};
</script>

<style lang="less">
.login-wrap {
  padding-top: 48rpx;
  .logo {
    display: block;
    width: 180rpx;
    height: 180rpx;
    border-radius: 50%;
    margin: auto;
  }

  .header {
    font-size: 42rpx;
    line-height: 58rpx;
    font-weight: 500;
    text-align: center;
    padding-top: 36rpx;
    margin-bottom: 120rpx;
  }
  .step {
    width: 600rpx;
    height: 468rpx;
    padding: 64rpx 48rpx 0;
    margin: auto;
    text-align: center;
    border-radius: 16rpx;
    background: #ffffff;

    &__title {
      font-size: 34rpx;
      margin-bottom: 32rpx;
      line-height: 48rpx;
      font-weight: 500;
    }

    &__desc {
      padding-left: 80rpx;
      font-size: 34rpx;
      color: #494949;
      line-height: 56rpx;
      text-align: left;
    }

    &__box {
      position: relative;
      width: 382rpx;
      height: 84rpx;
      margin: auto;
      margin-top: 24rpx;
    }

    &__btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 382rpx;
      height: 84rpx;
      margin: auto;
      font-size: 36rpx;
      border-radius: 42rpx;
      background-color: #fedd00;
    }
  }
}

.containar {
  .avatarUrl {
    padding: 80rpx 0 40rpx;
    background: #fff;

    button {
      background: #fff;
      line-height: 80rpx;
      height: auto;
      border: none !important;
      width: auto;
      margin: 0;
      display: flex;
      border: none;
      justify-content: center;
      align-items: center;

      &::after {
        border: none;
      }

      .refreshIcon {
        width: 160rpx;
        height: 160rpx;
        border-radius: 50%;
        background-color: #ccc;
      }

      .jt {
        width: 14rpx;
        height: 28rpx;
      }
    }
  }

  .userName {
    background: #fff;
    padding: 20rpx 30rpx 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    .weui-input {
      padding-left: 60rpx;
    }
  }

  .btn {
    width: 100%;
    .btn-sub {
      width: 670rpx;
      margin: 80rpx auto 0;
      height: 90rpx;
      background: #07C160;
      border-radius: 45rpx;
      line-height: 90rpx;
      text-align: center;
      font-size: 36rpx;
      color: #fff;
    }
  }
}
</style>